<!--
author:        hejy <silentmanager@163.com>
date:          2024-11-01 00:09:19
component:     index
Copyright © YourCompanyName All rights reserved
正在跟进
-->
<template>
  <div>
    <!-- 搜索表单 -->
    <el-card>
      <FormComponent :config="formConfig" ref="formRef">
        <template #submit>
          <div style="margin-left: 36px">
            <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" />搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" />重置</el-button>
            <el-button
              v-hasPermi="['crm:customer:recycling']"
              type="primary"
              @click="handleRecycling"
              >回收客户</el-button
            >
            <el-button type="primary" v-hasPermi="['crm:customer:tag']" @click="openMarkingDialog"
              >标记客户</el-button
            >
          </div>
        </template>
      </FormComponent>
    </el-card>

    <!-- 表格 -->
    <el-card style="margin-top: 24px">
      <el-alert :title="'已选择 ' + selectedCount + ' 项'" type="success" />
      <el-table
        :row-key="getRowKey"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        :data="list"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 + (queryParams.pageNo - 1) * queryParams.pageSize }}
          </template>
        </el-table-column>
        <el-table-column label="客户类型" prop="level" />
        <el-table-column label="客户名称" prop="name" />
        <el-table-column label="性别" prop="sex" />
        <el-table-column label="客户手机号" prop="mobile">
          <template #default="{ row }">
            <span>{{ formatPhoneNumber(row.mobile) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地址" prop="detailAddress" />
        <el-table-column label="分配人" prop="ownerUserName" />
        <el-table-column label="分配时间" prop="ownerTime" />
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <div style="display: flex">
              <el-button
                link
                type="primary"
                v-hasPermi="['bms:order-info:re-order']"
                @click="handlePlaceOrder(scope.row)"
                >下单</el-button
              >
              <el-button
                link
                type="warning"
                v-hasPermi="['crm:customer:remark:create']"
                @click="showDialog(scope.row)"
                >备注</el-button
              >
              <el-button
                v-hasPermi="['crm:customer:query']"
                link
                type="primary"
                @click="viewDetails(scope.row)"
                >详情</el-button
              >
              <el-button
                link
                type="primary"
                @click="handleEmit(scope.row)"
                v-hasPermi="['crm:customer:update']"
                >编辑</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 客户详情抽屉 -->
    <CustomerDetailDrawer
      v-model="isDetailDrawerVisible"
      :detailItem="detailItem"
      @success="getList"
    />
    <!-- 备注弹窗 -->
    <RemarkDialog :remarkId="remarkId" @success="getList" v-model:visible="isDialogVisible" />
    <!-- 编辑弹窗 -->
    <Emit v-model:visible="emitVisible" :emitData="emitData" @success="getList" />
    <!-- 标记弹窗 -->
    <Marking :selectId="selectId" ref="markingref" @success="getList" />
  </div>
</template>

<script lang="ts" setup>
import { CustomerEmitReq, pageCustomer, pageCustomerUser, putPoolCustomer } from '@/api/customer'
import CustomerDetailDrawer from '../wait-developed/components/detail.vue'
import FormComponent from '@/components/FormComponent/index.vue'
import { CustomerTypeOptions } from '@/mock/index'
import Marking from '../wait-developed/components/marking.vue'
import RemarkDialog from '../wait-developed/components/remark.vue'
import Emit from '../wait-developed/components/emit.vue'
import { defaultTime, formatPhoneNumber } from '@/utils'
import { defaultProps } from '@/utils/tree'
import { lockStatus, simpleListUser } from '@/api/order/create'
import { useDeptList } from '@/hooks/useDeptList'
import router from '@/router'
const message = useMessage()

// ----------------------------- 下单 -----------------------------
const handlePlaceOrder = async (row) => {
  try {
    const isLock = await lockStatus(row.mobile)
    const data = {
      customerPhone: row.mobile,
      customerName: row.name,
      address: row.detailAddress,
      customerType: row.level,
      gender: row.sex,
      age: row.age,
      lock: isLock.data
    }
    router.push({
      name: 'Creation',
      state: { data }
    })
  } catch (e) {
    console.error(e)
  }
}

// ----------------------------- 回收 -----------------------------
const handleRecycling = async () => {
  if (selectedCount.value === 0) {
    message.warning('请至少选择一位客户')
    return
  }
  try {
    await message.confirm('是否将选择客户回收带待开发中？')
    await putPoolCustomer(selectId.value.join(','))
    message.success('回收成功')
    getList()
  } catch (e) {
    console.error(e)
  }
}

// ----------------------------- 标记弹窗状态 -----------------------------
const markingref = ref<InstanceType<typeof Marking>>()
const openMarkingDialog = () => {
  if (selectedCount.value === 0) {
    message.warning('请至少选择一位客户')
    return
  }
  markingref.value?.open()
}

// ----------------------------- 编辑弹窗状态 -----------------------------
const emitData = ref<CustomerEmitReq>()
const emitVisible = ref<boolean>(false) // 定义对话框可见性的状态
// 显示弹窗的处理函数
const handleEmit = (row) => {
  emitData.value = {
    id: row.id,
    name: row.name,
    detailAddress: row.detailAddress,
    sex: row.sex
  }
  emitVisible.value = true
}

// ----------------------------- 详情抽屉状态 -----------------------------
const isDetailDrawerVisible = ref(false)
const detailItem = ref<pageCustomerUser>()
const viewDetails = (row) => {
  detailItem.value = row
  isDetailDrawerVisible.value = true // 打开详情抽屉
}
// ----------------------------- 备注弹窗状态 -----------------------------
const remarkId = ref(0)
const isDialogVisible = ref<boolean>(false) // 定义对话框可见性的状态
// 显示弹窗的处理函数
const showDialog = (row) => {
  remarkId.value = row.id
  isDialogVisible.value = true // 显示弹窗
}
// ==================== 表单  ====================
const formRef = ref<InstanceType<typeof FormComponent>>()
const { deptList } = useDeptList()
const userList = ref<{ label: string; value: number }[]>([])
const simpleListUserFn = async (deptId: string) => {
  try {
    if (!deptId) {
      return
    }
    const res = await simpleListUser({ deptId })
    userList.value = res.map((item) => {
      return {
        label: item.nickname,
        value: item.id
      }
    })
  } catch (e) {
    console.error(e)
  }
}

watch(
  [() => formRef.value?.formData.ownerTeamId],
  ([newTeam]) => {
    formRef.value?.setSingleData('allocateUser', '')
    simpleListUserFn(newTeam)
  },
  { deep: true }
)
const formConfig = ref([
  {
    label: '客户名称',
    prop: 'name',
    type: 'input',
    options: { placeholder: '请输入客户名称' }
  },
  {
    label: '客户类型',
    prop: 'level',
    type: 'select',
    options: {
      style: 'width: 240px',
      placeholder: '请选择客户类型',
      options: CustomerTypeOptions,
      filterable: true
    }
  },
  {
    label: '客户手机',
    prop: 'mobile',
    type: 'input',
    options: { placeholder: '请输入客户手机' }
  },
  {
    label: '分配人',
    prop: 'ownerTeamId',
    type: 'tree',
    options: {
      placeholder: '请选择分配组织',
      style: 'width: 240px',
      data: deptList,
      props: defaultProps,
      nodeKey: 'id',
      checkStrictly: true
    }
  },
  {
    label: '',
    prop: 'allocateUser',
    type: 'select',
    options: {
      placeholder: '请选择分配人',
      style: 'width: 240px',
      options: userList
    }
  },
  {
    label: '分配时间',
    prop: 'allocateTime',
    type: 'date',
    options: {
      type: 'datetimerange',
      defaultTime: defaultTime,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      rangeSeparator: '-',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间'
    }
  },
  {
    label: '回收时间',
    prop: 'recyclingTime',
    type: 'date',
    options: {
      type: 'datetimerange',
      defaultTime: defaultTime,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      rangeSeparator: '-',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间'
    }
  }
])

// --------------------  表格  ---------------------
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<pageCustomerUser[]>([]) // 列表的数据

// 分页
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10
})
// 定义选中项数量的状态
const selectedCount = ref(0)
const selectedQuantities = reactive<Record<string, number>>({})
const selectId = ref<number[]>([])
// 处理选择变化的函数
const handleSelectionChange = (selection: any[]) => {
  selectId.value = selection.map((item) => item.id)
  selectedCount.value = selection.length // 更新选中项的数量
}
// 生成包含 drinkId 和 num 的数组
const selectedItems = computed(() => {
  return selectId.value.map((id) => ({
    drinkId: id,
    num: selectedQuantities[id] || 0 // 默认数量为 0
  }))
})

defineExpose({ selectedItems })
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const [allocateTimeStart, allocateTimeEnd] = formRef.value?.formData.allocateTime || []
    const [recyclingTimeStart, recyclingTimeEnd] = formRef.value?.formData.recyclingTime || []
    const data = await pageCustomer({
      ...queryParams,
      ...formRef.value?.formData,
      tag: 5,
      allocateTimeStart,
      allocateTimeEnd,
      recyclingTimeStart,
      recyclingTimeEnd
    })
    list.value = data.list
    total.value = data.total
  } catch (e) {
    console.error(e)
    loading.value = false
  } finally {
    loading.value = false
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  formRef.value?.handleReset()
  handleQuery()
}
/** 初始化 */
onMounted(() => {
  getList()
})

const getRowKey = (row: any) => {
  return row.id
}
</script>
